<?php

/**
 * @user magein
 * @date 2024/1/19 14:36
 */

namespace magein\think\utils\traits;

use magein\utils\Tree;
use think\db\exception\DbException;

trait ModelTree
{

    /**
     * @return array
     */
    protected function floor(): array
    {
        $model = new self();
        $parent = '';
        $sort = '';
        if (property_exists($model, 'parent_filed')) {
            $parent = $model->parent_filed;
        }
        $parent = $parent ?: 'parent_id';

        if (property_exists($model, 'order_filed')) {
            $sort = $model->order_filed;
        }
        $sort = $sort ?: 'sort';

        try {
            $records = $model->order($sort . ' asc')->select()->toArray();
            $tree = Tree::init($records);
            $tree->setParentId($parent);
            $data = $tree->floor();
        } catch (DbException $exception) {
            $data = [];
        }

        return $data;
    }

    /**
     * @param $top
     * @param $separator
     * @return mixed|string[]
     */
    public static function selectOptions($top = null, $separator = null)
    {
        $options = $top ?: [0 => '顶级分类'];
        $separator = $separator ?: '|--';

        $model = new self();
        $data = $model->floor();
        $title = $model->title_filed ?: 'name';

        if ($data) {
            foreach ($data as $item) {
                $sp = '';
                $level = $item['__level__'];
                if ($level > 1) {
                    $sp = str_repeat($separator, ($level - 1));
                }
                $options[$item['id']] = $sp . ($item[$title] ?? '');
            }
        }
        return $options;
    }

    /**
     * @return array
     */
    public static function fetchFloor(): array
    {
        $model = new self();
        $data = $model->floor();
        $title = $model->title_filed ?: 'name';
        foreach ($data as $key => $item) {
            if ($item[$title] ?? '') {
                $nbsp = '';
                $level = $item['__level__'] ?? 0;
                if ($level > 1) {
                    $nbsp = str_repeat('&nbsp', ($level - 1) * 4);
                }
                $item[$title] = $nbsp . $item[$title];
            }
            $data[$key] = $item;
        }

        return $data;
    }
}